package org.jeecg.modules.wmhb.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.wmhb.vo.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 任务BOM
 * @Author: jeecg-boot
 * @Date: 2024-08-31
 * @Version: V1.0
 */
@Api(tags = "任务BOM")
@RestController
@RequestMapping("/wmhb/wmTaskBom")
@Slf4j
public class WmTaskBomController extends JeecgController<WmTaskBom, IWmTaskBomService> {
    @Autowired
    private IWmTaskBomService wmTaskBomService;
    @Autowired
    private IWmTaskService wmTaskService;
    @Autowired
    private IWmTaskbookService wmTaskbookService;
    @Autowired
    private IWmTaskFlowService wmTaskFlowService;
    @Autowired
    private IWmFlowDeptService wmFlowDeptService;
    @Autowired
    private IWmTaskLogService wmTaskLogService;

    /**
     * 分页列表查询
     *
     * @param wmTaskBom
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "任务BOM-分页列表查询")
    @ApiOperation(value = "任务BOM-分页列表查询", notes = "任务BOM-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmTaskBom>> queryPageList(WmTaskBom wmTaskBom,
                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                  HttpServletRequest req) {
        QueryWrapper<WmTaskBom> queryWrapper = QueryGenerator.initQueryWrapper(wmTaskBom, req.getParameterMap());
        Page<WmTaskBom> page = new Page<WmTaskBom>(pageNo, pageSize);
        IPage<WmTaskBom> pageList = wmTaskBomService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wmTaskBom
     * @return
     */
    @AutoLog(value = "任务BOM-添加")
    @ApiOperation(value = "任务BOM-添加", notes = "任务BOM-添加")
    @RequiresPermissions("wmhb:wm_task_bom:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody WmTaskBom wmTaskBom) {
        wmTaskBomService.save(wmTaskBom);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wmTaskBom
     * @return
     */
    @AutoLog(value = "任务BOM-编辑")
    @ApiOperation(value = "任务BOM-编辑", notes = "任务BOM-编辑")
    @RequiresPermissions("wmhb:wm_task_bom:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody WmTaskBom wmTaskBom) {
        wmTaskBomService.updateById(wmTaskBom);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务BOM-通过id删除")
    @ApiOperation(value = "任务BOM-通过id删除", notes = "任务BOM-通过id删除")
    @RequiresPermissions("wmhb:wm_task_bom:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        wmTaskBomService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "任务BOM-批量删除")
    @ApiOperation(value = "任务BOM-批量删除", notes = "任务BOM-批量删除")
    @RequiresPermissions("wmhb:wm_task_bom:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.wmTaskBomService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "任务BOM-通过id查询")
    @ApiOperation(value = "任务BOM-通过id查询", notes = "任务BOM-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmTaskBom> queryById(@RequestParam(name = "id", required = true) String id) {
        WmTaskBom wmTaskBom = wmTaskBomService.getById(id);
        if (wmTaskBom == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(wmTaskBom);
    }

    /**
     * 合并导出报料BOM
     *
     * @param request
     * @param wmTaskids
     */
    @RequiresPermissions("wmhb:wm_task_bom:exportApplyXls")
    @RequestMapping(value = "/exportApplyXls")
    @ApiOperation(value = "任务BOM-合并导出报料BOM", notes = "任务BOM-合并导出报料BOM")
    public ModelAndView exportApplyXls(HttpServletRequest request, @RequestParam(name = "wmTaskids", required = true) String wmTaskids) {
        List<String> idList = Arrays.asList(wmTaskids.split(","));
        List<WmTaskBom> wmTaskBomList = wmTaskBomService.baoliaoListByWmTaskIds(idList);
        if(wmTaskBomList.isEmpty()){
            throw new RuntimeException("当前任务没有物料");
        }
        WmTask wmTask = wmTaskService.getById(idList.get(0));
        return wmTaskBomService.exportBomExcel(request, wmTask.getTaskbookType(), wmTaskBomList);
    }

    /**
     * 通过excel导入核减单数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("wmhb:wm_task_bom:importApplyExcel")
    @RequestMapping(value = "/importApplyExcel", method = RequestMethod.POST)
    @ApiOperation(value = "任务BOM-导入核减单数据", notes = "任务BOM-导入核减单数据")
    @Transactional
    public Result<?> importApplyExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            Integer sheetNum = 1;
            Workbook workbook = null;
            try {
                workbook = WorkbookFactory.create(file.getInputStream());
                sheetNum = workbook.getNumberOfSheets();//读取sheet的数量
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }

            ImportParams params = new ImportParams();
            params.setStartSheetIndex(0); //从第几个sheet页开始读取
            params.setSheetNum(sheetNum); //读取几个sheet页
            params.setTitleRows(0);       //标题行数
            params.setHeadRows(1);        //头部行数
            params.setNeedSave(false);    //是否保存文件
            try {
                List<WmHjdBomVo> list = ExcelImportUtil.importExcel(file.getInputStream(), WmHjdBomVo.class, params);
                WmHjdBomResult wmHjdBomResult = uploadApplyProcess(list);
                return Result.ok(wmHjdBomResult);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new RuntimeException(e.getMessage());
            } finally {
                try {
                    workbook.close();
                    file.getInputStream().close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    private WmHjdBomResult uploadApplyProcess(List<WmHjdBomVo> list){
        List<WmHjdBomVo> newList = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String batchNo = format.format(new Date());
        try {
            for (WmHjdBomVo bomNode : list) {
                bomNode.setStatus("正常");
                if (StringUtils.isEmpty(bomNode.getSeriesNo()) && StringUtils.isEmpty(bomNode.getSeriesNo2())) {
                    bomNode.setStatus("物料序号缺失");
                    newList.add(bomNode);
                    continue;
                }

                if(bomNode.getPurchaseNum() == null){
                    throw new RuntimeException("采购数量不能为空");
                }

                //更新任务BOM状态为已下单和下单数量
                WmApplyBomVo wmApplyBomVo = new WmApplyBomVo();
                wmApplyBomVo.setPurchaseNum(bomNode.getPurchaseNum());
                wmApplyBomVo.setSeriesNo(bomNode.getSeriesNo());
                if(!StringUtils.isEmpty(bomNode.getSeriesNoAuto())){
                    if(!StringUtils.isEmpty(bomNode.getSeriesNo2())) {
                        wmApplyBomVo.setSeriesNo(bomNode.getSeriesNo2());
                    }

                    //更新自动生成的序号为手动生成的序号，以及备用如果有使用，则更新报料清单
                    WmTaskBom wmTaskBom = wmTaskBomService.queryBySeriesNo(bomNode.getSeriesNoAuto());
                    wmTaskBom.setSeriesNo(wmApplyBomVo.getSeriesNo());
                    wmTaskBom.setName(bomNode.getName());
                    if(!StringUtils.isEmpty(bomNode.getName2())) {
                        wmTaskBom.setName(bomNode.getName2());
                    }
                    wmTaskBom.setCode(bomNode.getCode());
                    wmTaskBom.setSpecification(bomNode.getSpecification());
                    if(!StringUtils.isEmpty(bomNode.getSpecification2())) {
                        wmTaskBom.setSpecification(bomNode.getSpecification2());
                    }
                    wmTaskBom.setUnitOfMeasure(bomNode.getUnitOfMeasure());
                    wmTaskBom.setCaiLiao(bomNode.getCaiLiao());
                    wmTaskBom.setMingCheng(bomNode.getMingCheng());
                    wmTaskBom.setGbNumber(bomNode.getGbNumber());
                    wmTaskBom.setOtherRequire(bomNode.getOtherRequire());
                    wmTaskBom.setMaterial(bomNode.getMaterial());
                    wmTaskBom.setNeedNum(bomNode.getNeedNum());
                    if(bomNode.getNeedNum2() != null) {
                        wmTaskBom.setNeedNum(bomNode.getNeedNum2());
                    }
                    wmTaskBom.setPurchaseNum(bomNode.getPurchaseNum());
                    wmTaskBom.setGotowhere(bomNode.getGotowhere());
                    if(StringUtils.isEmpty(bomNode.getGotowhere2())){
                        wmTaskBom.setGotowhere(bomNode.getGotowhere2());
                    }
                    wmTaskBomService.updateById(wmTaskBom);//更新TASK BOM
                }
                wmTaskBomService.updatePurchaseNum(wmApplyBomVo);

                //更新任务状态为已核减
                String wmTaskId = wmTaskBomService.selectWmTaskIdBySeriesNo(wmApplyBomVo.getSeriesNo());
                WmTask wmTask = wmTaskService.getById(wmTaskId);
                if((wmTask.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PRODUCE_ELECTRIC) && wmTask.getStatus().equals(UserConstant.TASK_STATUS_DESIGN_APPROVED))
                || (wmTask.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PRODUCE) && wmTask.getStatus().equals(UserConstant.TASK_STATUS_PRODUCE_APPROVED))){
                    //获取所有子任务(包括自己)
                    List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
                    for(WmTask wmTaskItem: wmTaskList) {
                        wmTaskItem.setStatus(UserConstant.TASK_STATUS_ORDERED); //更新任务的状态为已核减
                        wmTaskItem.setProgress("40");//已核减算40%
                        //下一流程
                        nextFlowTask(wmTaskItem);

                        //判断同级的任务是否都已核减，有则更新父任务和任务书的当前部门信息
                        if(wmTaskItem.getId().equals(wmTask.getId())) {
                            sameLevelTaskCheck(wmTaskItem);

                            //更新任务日志
                            wmTaskLogService.updateTaskLog(wmTaskItem.getId(), UserConstant.TASK_LOG_TYPE_BOM_ORDER);
                        }
                    }
                }

                newList.add(bomNode);
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        WmHjdBomResult wmHjdBomResult = new WmHjdBomResult();
        wmHjdBomResult.setApplyBomList(newList);
        wmHjdBomResult.setBatchNo(batchNo);
        return wmHjdBomResult;
    }

    //如果同级别的任务都大于当前任务的当前部门序号，则更新父任务和任务书的当前部门信息
    private void sameLevelTaskCheck(WmTask wmTask){
        Boolean flag = true;
        List<WmTask> wmTaskList = wmTaskService.sameLevelTask(wmTask);
        for(WmTask wmTaskItem: wmTaskList){
            //判断同级任务是否都大于当前任务的当前部门序号
            if(wmTaskItem.getCurrentNodeIndex() < wmTask.getCurrentNodeIndex()){
                flag = false;
            }

            if(wmTaskItem.getId().equals(wmTask.getId())){
                //从数据库中获取最新的当前任务
                wmTask = wmTaskItem;
            }
        }

        if(flag){
            //更新祖先任务当前部门信息
            List<WmTask> ancestorTaskList = wmTaskService.ancestorTask(wmTask);
            if(!ancestorTaskList.isEmpty()) {
                for(WmTask wmTaskItem: ancestorTaskList) {
                    wmTaskItem.setCurrentNodeId(wmTask.getCurrentNodeId());
                    wmTaskItem.setCurrentNodeIndex(wmTask.getCurrentNodeIndex());
                    wmTaskItem.setCurrentNodeTime(new Date());
                    wmTaskItem.setProgress(wmTask.getProgress());
                    wmTaskItem.setStatus(wmTask.getStatus());
                    wmTaskService.updateById(wmTaskItem);
                }
            }

            //更新任务书当前部门信息
            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
            wmTaskbook.setCurrentNodeId(wmTask.getCurrentNodeId());
            wmTaskbook.setCurrentNodeIndex(wmTask.getCurrentNodeIndex());
            wmTaskbook.setProgress(wmTask.getProgress());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbookService.updateById(wmTaskbook);
        }
    }

    /**
     * 通过excel导入订货明细
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("wmhb:wm_task_bom:importOrderExcel")
    @RequestMapping(value = "/importOrderExcel", method = RequestMethod.POST)
    @ApiOperation(value = "任务BOM-导入订货明细", notes = "任务BOM-导入订货明细")
    @Transactional
    public Result<?> importOrderExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            Integer sheetNum = 1;
            Workbook workbook = null;
            try {
                workbook = WorkbookFactory.create(file.getInputStream());
                sheetNum = workbook.getNumberOfSheets();//读取sheet的数量
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage());
            }

            ImportParams params = new ImportParams();
            params.setStartSheetIndex(0); //从第几个sheet页开始读取
            params.setSheetNum(sheetNum); //读取几个sheet页
            params.setTitleRows(1);       //标题不能为空，否则跳过该行
            params.setHeadRows(1);
            params.setNeedSave(false);
            try {
                List<WmOrderBomVo> list = ExcelImportUtil.importExcel(file.getInputStream(), WmOrderBomVo.class, params);
                WmOrderBomResult wmOrderBomResult = uploadOrderProcess(list);
                return Result.ok(wmOrderBomResult);
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                throw new RuntimeException(e.getMessage());
            } finally {
                try {
                    workbook.close();
                    file.getInputStream().close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.error("文件导入失败！");
    }

    private WmOrderBomResult uploadOrderProcess(List<WmOrderBomVo> list){
        List<WmOrderBomVo> newList = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String batchNo = format.format(new Date());
        try {
            List<String> wmTaskIdList = new ArrayList<>();
            for (WmOrderBomVo bomNode : list) {
                bomNode.setStatus("正常");
                if (StringUtils.isEmpty(bomNode.getSeriesNo())) {
                    bomNode.setStatus("物料序号缺失");
                    newList.add(bomNode);
                    continue;
                }

                String wmTaskId = wmTaskBomService.selectWmTaskIdBySeriesNo(bomNode.getSeriesNo());
                if(!StringUtils.isEmpty(wmTaskId) && !wmTaskIdList.contains(wmTaskId)) {
                    wmTaskIdList.add(wmTaskId);
                }

                wmTaskBomService.updateOrderDetail(bomNode);
                newList.add(bomNode);
            }

            //判断任务BOM是否全部采购和到货
            for(String wmTaskId: wmTaskIdList){
                List<String> taskIdList = new ArrayList<>();
                taskIdList.add(wmTaskId);
                WmTask wmTask = wmTaskService.getById(wmTaskId);

                //只更新已核减状态下的任务及其子任务
                List<String> statusList = new ArrayList<>();
                statusList.add(UserConstant.TASK_STATUS_ORDERED);
                statusList.add(UserConstant.TASK_STATUS_PURCHASED);
                if(statusList.contains(wmTask.getStatus())) {
                    List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTask);
                    List<WmTaskBom> baoliaoTaskBomList = wmTaskBomService.baoliaoListByWmTaskIds(taskIdList);//待报料或已核减物料
                    List<WmTaskBom> noArriveTaskBomList = wmTaskBomService.noArriveListByWmTaskId(wmTaskId); //物料未到齐
                    for(WmTask wmTaskItem: wmTaskList) {
                        //报料初始状态和已核减状态物料列表为空时，说明任务的物料全部进入采购状态或之后的状态
                        if (baoliaoTaskBomList.isEmpty()) {
                            //物料已采购
                            wmTaskItem.setStatus(UserConstant.TASK_STATUS_PURCHASED);
                            //更新任务日志
                            wmTaskLogService.updateTaskLog(wmTaskItem.getId(), UserConstant.TASK_LOG_TYPE_BOM_PURCHASE);
                        }
                        //任务物料列表没有未到货的
                        if (noArriveTaskBomList.isEmpty()) {
                            //物料已到货
                            wmTaskItem.setStatus(UserConstant.TASK_STATUS_BOM_REACHED);
                            //更新任务日志
                            wmTaskLogService.updateTaskLog(wmTaskItem.getId(), UserConstant.TASK_LOG_TYPE_BOM_REACHED);
                        }
                        wmTaskService.updateById(wmTaskItem);

                        //更新任务书信息
                        if(wmTaskItem.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
                            WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
                            wmTaskbook.setProgress(wmTaskItem.getProgress());
                            wmTaskbook.setStatus(wmTaskItem.getStatus());
                            wmTaskbook.setCurrentNodeIndex(wmTaskItem.getCurrentNodeIndex());
                            wmTaskbook.setCurrentNodeId(wmTaskItem.getCurrentNodeId());
                            wmTaskbookService.updateById(wmTaskbook);
                        }
                    }

                    //判断同级的任务是否都已采购或已到货，有则更新父任务和任务书的当前部门信息
                    sameLevelTaskCheck(wmTask);
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }

        WmOrderBomResult wmOrderBomResult = new WmOrderBomResult();
        wmOrderBomResult.setOrderBomList(newList);
        wmOrderBomResult.setBatchNo(batchNo);
        return wmOrderBomResult;
    }

    /**
     * 物料退还
     *
     * @param wmTaskBomId
     * @param num
     * @return
     */
    @AutoLog(value = "任务BOM-物料退还")
    @ApiOperation(value = "任务BOM-物料退还", notes = "任务BOM-物料退还")
    @RequiresPermissions("wmhb:wm_task_bom:returnBom")
    @RequestMapping(value = "/returnBom", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> returnBom(@RequestParam(name = "wmTaskBomId", required = true) String wmTaskBomId, @RequestParam(name = "num", required = true) String num) {
        WmTaskBom wmTaskBom = wmTaskBomService.getById(wmTaskBomId);
        if(wmTaskBom == null){
            return Result.error("任务BOM不存在");
        }

        Double totalReturnNum = wmTaskBom.getReturnNum() + Double.parseDouble(num);
        if(totalReturnNum > wmTaskBom.getNeedNum()){
            return Result.error("退还数量不能大于设计数量");
        }

        Double canReturnNum = wmTaskBom.getArriveNum() + wmTaskBom.getNeedNum() - wmTaskBom.getPurchaseNum();//退还数量不能大于库存数量与到货数量之和
        if(totalReturnNum > canReturnNum){
            return Result.error("退还数量不能大于库存数量与到货数量之和");
        }
        wmTaskBom.setReturnNum(totalReturnNum);
        wmTaskBomService.updateById(wmTaskBom);
        return Result.OK("操作成功!");
    }

    /**
     * 物料废除
     *
     * @param wmTaskBomId
     * @param num
     * @return
     */
    @AutoLog(value = "任务BOM-物料废除")
    @ApiOperation(value = "任务BOM-物料废除", notes = "任务BOM-物料废除")
    @RequiresPermissions("wmhb:wm_task_bom:wasteBom")
    @RequestMapping(value = "/wasteBom", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> wasteBom(@RequestParam(name = "wmTaskBomId", required = true) String wmTaskBomId, @RequestParam(name = "num", required = true) String num) {
        WmTaskBom wmTaskBom = wmTaskBomService.getById(wmTaskBomId);
        if(wmTaskBom == null){
            return Result.error("任务BOM不存在");
        }

        Double totalWasteNum = wmTaskBom.getWasteNum() + Double.parseDouble(num);
        if(totalWasteNum > wmTaskBom.getNeedNum()){
            return Result.error("废除数量不能大于设计数量");
        }
        Double canReturnNum = wmTaskBom.getArriveNum() + wmTaskBom.getNeedNum() - wmTaskBom.getPurchaseNum();//废除数量不能大于库存数量与到货数量之和
        if(totalWasteNum > canReturnNum){
            return Result.error("废除数量不能大于库存数量与到货数量之和");
        }

        wmTaskBom.setWasteNum(totalWasteNum);
        wmTaskBomService.updateById(wmTaskBom);
        return Result.OK("操作成功!");
    }

    /**
     * 任务下一流程
     * @param wmTask
     * @return
     */
    private void nextFlowTask(WmTask wmTask){
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
        //1、流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());

        //2、下一流程
        Integer nextIndex = wmTask.getCurrentNodeIndex() + 1;
        if(nextIndex >= wmFlowDeptList.size()){
            if(wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_TECHNOLOGY)){
                //技术服务任务书设计提交后没有下一流程（技术服务设计和调试是一个部门）
                wmTaskService.updateById(wmTask);
                return;
            }
            else{
                throw new RuntimeException("请补充完整的流程定义");
            }
        }

        //3、更改子任务的当前流程节点及时间信息
        WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), nextIndex - 1);
        WmTaskFlow wmTaskFlowNext = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), nextIndex);
        wmTaskFlowCurr.setFactEndTime(new Date());
        wmTaskFlowNext.setFactBeginTime(new Date());
        wmTaskFlowService.updateById(wmTaskFlowCurr);
        wmTaskFlowService.updateById(wmTaskFlowNext);

        //4、更新子任务当前节点
        wmTask.setCurrentNodeTime(new Date());
        wmTask.setCurrentNodeId(wmFlowDeptList.get(nextIndex).getDeptId());
        wmTask.setCurrentNodeIndex(nextIndex);
        wmTaskService.updateById(wmTask);

        //5、更新任务书当前流程部门
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            wmTaskbook.setProgress(wmTask.getProgress());
            wmTaskbook.setStatus(wmTask.getStatus());
            wmTaskbook.setCurrentNodeIndex(nextIndex);
            wmTaskbook.setCurrentNodeId(wmFlowDeptList.get(nextIndex).getDeptId());
            wmTaskbookService.updateById(wmTaskbook);
        }
    }

    /**
     * 任务上一流程
     * @param wmTask
     * @return
     */
    private void prevFlowTask(WmTask wmTask){
        WmTaskbook wmTaskbook = wmTaskbookService.getById(wmTask.getWmTaskbookId());
        //1、流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());

        //2、上一流程
        Integer prevIndex = wmTask.getCurrentNodeIndex() - 1;
        if(prevIndex < 0){
            throw new RuntimeException("流程异常");
        }

        //3、更改子任务的当前流程节点及时间信息
        WmTaskFlow wmTaskFlowPrev = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), prevIndex);
        WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), prevIndex + 1);
        wmTaskFlowPrev.setFactEndTime(null);
        wmTaskFlowCurr.setFactBeginTime(null);
        wmTaskFlowService.updateById(wmTaskFlowPrev);
        wmTaskFlowService.updateById(wmTaskFlowCurr);

        //4、更新子任务当前节点
        wmTask.setCurrentNodeTime(new Date());
        wmTask.setCurrentNodeId(wmFlowDeptList.get(prevIndex).getDeptId());
        wmTask.setCurrentNodeIndex(prevIndex);
        wmTaskService.updateById(wmTask);

        //5、更新任务书当前流程部门
        if(wmTask.getAncestors().equals(UserConstant.ANCESTOR_ZERO)) {
            wmTaskbook.setCurrentNodeIndex(prevIndex);
            wmTaskbook.setCurrentNodeId(wmFlowDeptList.get(prevIndex).getDeptId());
            wmTaskbookService.updateById(wmTaskbook);
        }
    }
}
